package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Vibrator
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.jt.assistant.R
import com.jt.assistant.adapter.ScanAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.base.GlobalConfig.STORE_ROLE
import com.jt.assistant.base.GlobalConfig.TRANSFERSUPERVISOR
import com.jt.assistant.bean.OnKeyScanCarton
import com.jt.assistant.bean.ScanCarton
import com.jt.assistant.bean.ScanDataBean
import com.jt.assistant.utils.FastClickUtil
import com.jt.assistant.utils.ScanCartonCodeHelper
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_scan.*
import java.util.regex.Pattern

/**
 * 送仓扫码
 */
class ScanActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        ScanAdapter(
            ArrayList<ScanCarton>()
        )
    }
    private var mScanData: ScanDataBean? = null
    private val mScanCartonList = ArrayList<ScanCarton>()
    private val mOneKeyScanCartonList = ArrayList<OnKeyScanCarton>()
    private val mHandle by lazy { Handler() }


    private val mRunnable = Runnable {
        val mUploadList = ArrayList<ScanCarton>()
        mScanCartonList.forEach {
            if (it.hasScan && !it.hasUpload) {
                mUploadList.add(it)
            }
        }
        viewModel.sendScanLog(mUploadList)
    }


    //循环查询一键扫码状态
    private val mLoopCheckRunnable = Runnable {
        viewModel.onekeyScanQuery(mOneKeyScanCartonList)
        checkStatus()
    }

    override fun onDestroy() {
        set_scan.unregisterEventBus()
        if (mHandle.hasCallbacks(mLoopCheckRunnable)) {
            mHandle.removeCallbacks(mLoopCheckRunnable)
        }
        super.onDestroy()
    }

    override fun layoutId(): Int = R.layout.activity_scan

    override fun initView(savedInstanceState: Bundle?) {
        set_scan.initCamera(this, GlobalConfig.SCAN_TYPE_OUT)
        with(rv_scan) {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        mScanData = GsonUtils.fromJson(
            intent.getStringExtra(GlobalConfig.SCAN_DATA).toString(),
            ScanDataBean::class.java
        )
        mScanCartonList.addAll(ScanCartonCodeHelper.createScanList(mScanData!!))
        log(mScanCartonList)

        val states = resources.getStringArray(R.array.waybill_state_name)
        if (states[mScanData!!.state] == "待提货" || states[mScanData!!.state] == "已提货") {
            bt_totalCarton.text = "总箱数: ${mScanData!!.waybillList[0].cartonNum}"
            bt_ScanCarton.text = "已扫码: ${scanNumber()}"
        } else {
            bt_totalCarton.text = "总箱数: ${mScanData!!.totalCarton}"
            bt_ScanCarton.text = "已扫码: ${scanNumber()}"
        }


        //一键扫码
        val scanState = ScanCartonCodeHelper.getScanState(mScanData!!)
        val dispatchCarId = mScanData!!.dispatchCarId + ""
        mScanData!!.waybillList.forEach {
            if (it.supportOnceScan == 1) {
                tv_oneKey.text = "${tv_oneKey.text}${it.waybillNo}\n"
                ll_oneKey.visibility = View.VISIBLE
                mOneKeyScanCartonList.add(
                    OnKeyScanCarton(
                        it.waybillNo,
                        scanState,
                        dispatchCarId + ""
                    )
                )
            }
        }


        //如果是转运中心的人,将之前上报的全部重新上报一次,
        //1.将数据全部未上传
        //2.在未上传数据中找出已经扫码的箱码上传
        //转运中心 203588829 203587646
        if (MMKV.defaultMMKV().getString("ROLENAMELIST", "").toString().contains(TRANSFERSUPERVISOR)
            || MMKV.defaultMMKV().getString("ROLENAMELIST", "").toString().contains(STORE_ROLE)
        ) {

            for (i in mScanCartonList.indices) {
                mScanCartonList[i].hasUpload = false

                if (mScanCartonList[i].hasScan) {
                    mAdapter.data.add(mScanCartonList[i])
                    mAdapter.notifyDataSetChanged()
                }

            }
            bt_ScanCarton.text = "已扫码: ${scanNumber()}"
            viewModel.sendScanLog(mAdapter.data)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        set_scan.setOnScanListener {
            if (it.isNullOrEmpty()) {
                ToastUtils.showShort("请输入箱码")
                set_scan.clearData()
                return@setOnScanListener
            }
            if (!checkCartonCode(it)) {
                set_scan.clearData()
                return@setOnScanListener
            }
            hasScanData()
            set_scan.clearData()
        }


        tv_upload.setOnClickListener {
            //手动上报
            if (FastClickUtil.isFastClick()) { //防重复点击
                return@setOnClickListener
            }

            val uploadList = ArrayList<ScanCarton>()
            mScanCartonList.forEach {
                if (it.hasScan && !it.hasUpload) {
                    uploadList.add(it)
                }
            }

            if (uploadList.size == 0) {
                speakString("数据已上传")
                return@setOnClickListener
            }
            if (mHandle.hasCallbacks(mRunnable)) {
                mHandle.removeCallbacks(mRunnable)
            }
            viewModel.sendScanLog(uploadList)
        }

        bt_totalCarton.setOnClickListener {
            MMKV.defaultMMKV()
                .putString(
                    GlobalConfig.SCAN_DATA,
                    intent.getStringExtra(GlobalConfig.SCAN_DATA).toString()
                )
            MMKV.defaultMMKV().putString(
                GlobalConfig.SCAN_CARTON_LIST, GsonUtils.toJson(
                    mScanCartonList
                )
            )
            startActivity(Intent(this@ScanActivity, WaybillStateActivity::class.java))
        }

        bt_ScanCarton.setOnClickListener {
            MMKV.defaultMMKV().putString(
                GlobalConfig.SCAN_CARTON_LIST, GsonUtils.toJson(
                    mScanCartonList
                )
            )
            startActivity(Intent(this@ScanActivity, CartonStateActivity::class.java))
        }


        bt_oneKey.setOnClickListener {
            //一键扫码
            viewModel.oneKeyScan(mOneKeyScanCartonList)
        }

        //上传的箱码回传
        viewModel.mScanCarton.observe(this, {
            //将数据置为已上传状态
            it.forEach {
                Logger.e("########${it.cartonCode}")
                for (position in mScanCartonList.indices) {
                    if (it.cartonCode == mScanCartonList[position].cartonCode && !mScanCartonList[position].hasUpload) {
                        mScanCartonList[position].hasUpload = true
                    }
                }
            }
            bt_ScanCarton.text = "已扫码: ${scanNumber()}"
            ToastUtils.showShort("上传成功")
            updateList()
            if (scanNumber().toInt() >= mScanCartonList.size) {//mScanCartonList
                speakString("扫码已完成")
                finish()
            }
        })


        viewModel.mSendScanLog.observe(this, {
            if (it.isSuccess()) {
                tv_codeListStatus.setTextColor(Color.GRAY)
                tv_codeListStatus.text = "待上传列表"
            } else {
                tv_codeListStatus.text = "上传失败请手动上传"
                tv_codeListStatus.setTextColor(Color.RED)
            }
        })


        viewModel.mOneKeyScan.observe(this, {
            if (it.isSuccess()) {
                showLoading()
                ToastUtils.showShort("一键扫码后台处理中")
                checkStatus()
                ll_oneKey.visibility = View.GONE
            }
        })

        viewModel.mOnekeyScanQuery.observe(this, {
            dismissLoading()
            if (it.isSuccess()) {
                if (it.data) {
                    if (mHandle.hasCallbacks(mLoopCheckRunnable)) {
                        mHandle.removeCallbacks(mLoopCheckRunnable)
                    }

                    speakString("一键扫码成功")
                    //箱码设置为已扫码状态
                    mOneKeyScanCartonList.forEach {
                        for (position in mScanCartonList.indices) {
                            if (it.waybillNo == mScanCartonList[position].waybillNo) {
                                mScanCartonList[position].hasUpload = true
                                mScanCartonList[position].hasScan = true
                            }
                        }
                    }
                    bt_ScanCarton.text = "已扫码: ${scanNumber()}"

                    if (scanNumber().toInt() >= mScanData!!.totalCarton) {
                        speakString("扫码已完成")
                        finish()
                        return@observe
                    }
                }
            } else {
                if (mHandle.hasCallbacks(mLoopCheckRunnable)) {
                    mHandle.removeCallbacks(mLoopCheckRunnable)
                }
                showDialog()
            }
        })

    }

    private fun scanNumber(): String {
        var num = 0
        mScanCartonList.forEach {
            if (it.hasScan && it.hasUpload) {
                num++
            }
        }
        return num.toString()
    }

    override fun handleEvent(msg: String) {
        speakString("上传失败请检查网络")
        ToastUtils.showShort("网络请求失败,上传失败请检查网络: $msg")
    }

    private fun checkCartonCode(code: String): Boolean {
        if (!isCartonCode(code)) {
            speakString("箱码错误")
            return false
        }

        for (position in mScanCartonList.indices) {
            if (code == mScanCartonList[position].cartonCode) {
                return if (mScanCartonList[position].hasScan) {
                    speakString("重复扫码")
                    false
                } else {
                    //将数据置为已扫码状态
                    mScanCartonList[position].hasScan = true
                    mAdapter.data.add(0, mScanCartonList[position])
                    mAdapter.notifyDataSetChanged()
                    vibrate()
                    true
                }
            }
        }//1234567891185000001 201015641602000010

        if (code.length != 18) {
            speakString("箱码错误")
            return false
        }

        for (position in mScanCartonList.indices) {
            val oldCode = "${code.subSequence(0, 11)}${code.subSequence(13, 18)}"
            val newCode = "${
                mScanCartonList[position].cartonCode.subSequence(
                    0,
                    11
                )
            }${mScanCartonList[position].cartonCode.subSequence(13, 18)}"

            if (oldCode == newCode) {
                return if (mScanCartonList[position].hasScan) {
                    speakString("重复扫码")
                    false
                } else {
                    //将数据置为已扫码状态
                    mScanCartonList[position].cartonCode = code
                    mScanCartonList[position].hasScan = true
                    mAdapter.data.add(0, mScanCartonList[position])
                    mAdapter.notifyDataSetChanged()
                    vibrate()
                    true
                }
            }
        }

        speakString("箱码错误")
        return false
    }


    private fun updateList() {
        mAdapter.data.clear()
        mScanCartonList.forEach {
            if (it.hasScan && !it.hasUpload) {
                mAdapter.data.add(0, it)
            }
        }
        mAdapter.notifyDataSetChanged()
    }


    private fun hasScanData() {
        if (mHandle.hasCallbacks(mRunnable)) {
            mHandle.removeCallbacks(mRunnable)
        }
        mHandle.postDelayed(mRunnable, 3000)

    }

    private fun checkStatus() {
        mHandle.postDelayed(mLoopCheckRunnable, 3000)
    }

    private fun showDialog() {
        MaterialDialog(this).show {
            title(null, "一键扫码失败,是否重试")
            cornerRadius(8f)
            positiveButton(null, "确定") {
                viewModel.oneKeyScan(mOneKeyScanCartonList)

            }
            lifecycleOwner(this@ScanActivity)
        }
    }

    private fun vibrate() {
        val vibrator: Vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    private fun isCartonCode(cartonCode: String): Boolean {
        //check cartonCode
        if (TextUtils.isEmpty(cartonCode)) {
            return false
        }
        val newCarton = "^[a-zA-Z0-9]{15}-\\d+-\\d+-$"
        val numberCarton = "^[0-9]{18}$"
        val patternNew = Pattern.compile(newCarton)
        val patternNum = Pattern.compile(numberCarton)
        return patternNum.matcher(cartonCode).find() || patternNew.matcher(cartonCode).find()
    }
}